package com.kaikeba.estack.dao.imp;


import com.kaikeba.estack.bean.User;
import com.kaikeba.estack.common.jdbc.DataSourceUtil;
import com.kaikeba.estack.common.jdbc.JdbcUtil;
import com.kaikeba.estack.dao.UserDao;
import com.kaikeba.estack.exception.DataAccessException;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class UserDaoMysql extends BaseDaoImpl<User> implements UserDao {

    private static final String TABLE_NAME = "e_user";

    private static final String SQL_UPDATE_LOGIN_TIME = "update e_user set last_login_time=?,last_login_ip=?,login_times = login_times + 1 where username=?";

    private static final String SQL_LOGIN = "select * from e_user where username=? and password=? and is_del = 0";

    /**
     * 根据用户名，更新登陆时间和登录ip
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        try {
            JdbcUtil.execute(DataSourceUtil.getConnection(), SQL_UPDATE_LOGIN_TIME, date, ip, username);
        } catch (SQLException sqlException) {
            throw new DataAccessException(sqlException);
        }
    }

    /**
     * 管理员根据账号密码登陆
     *
     * @param username 账号
     * @param password 密码
     * @return 登陆的结果， true表示登陆成功
     */
    @Override
    public List<User> queryUserByUsernamePassword(String username, String password) {
        try {
            return JdbcUtil.queryForList(DataSourceUtil.getConnection(), SQL_LOGIN, User.class, username, password);
        } catch (SQLException sqlException) {
            throw new DataAccessException(sqlException);
        }
    }

    @Override
    public String getTableName() {
        return TABLE_NAME;
    }
}
